<script lang="ts" setup>
import { useI18n } from 'vue-i18n'

import { useSheetSelector } from './composables/useSheetSelector'
import type { Student } from './composables/useStudentImport'
import { useExcel } from '@/composables/useExcel'
import { useCheckbox } from '@/composables/useCheckbox'

const emits = defineEmits<{ 'students-import': [students: Student[]]; test: [v: number] }>()
const { t } = useI18n<[typeof import('./locales/zh-CN.json')]>({ useScope: 'parent' })
const { options, checked, isCheckedAll, indeterminate, toggleIndeterminate } = useCheckbox<string>()
const { visible, closeModal, resolveSelect, selectSheet } = useSheetSelector(options, checked)
const { openExcel, onParsed } = useExcel<Record<'学号' | '姓名' | '密码', string>, Student>({
  sheetFilter: selectSheet,
  mapper: ({ 学号, 姓名, 密码 }) => ({
    username: String(学号),
    name: String(姓名),
    password: String(密码)
  })
})

onParsed((students) => {
  /** @desc 过滤重复项与 undefined */
  const uniqueStudents = new Set(students.map(({ username }) => username))
  const cleanStudents = students.filter((student) => {
    const allDefined = student.username && student.name && student.password
    if (allDefined && uniqueStudents.has(student.username)) {
      uniqueStudents.delete(student.username)
      return true
    }
    return false
  })

  emits('students-import', cleanStudents)
})
</script>

<template>
  <a-button size="mini" type="dashed" status="success" @click="openExcel">
    <VscodeIconsFileTypeExcel class="text-lg mr-1" />
    {{ t('sheetSelector.import') }}
    <a-modal :visible @ok="resolveSelect" @cancel="closeModal">
      <template #title>{{ t('sheetSelector.multiple') }}</template>
      <div>
        <a-checkbox :modelValue="isCheckedAll" :indeterminate @change="toggleIndeterminate">
          {{ t('sheetSelector.checkAll') }}
        </a-checkbox>
      </div>

      <a-checkbox-group v-model="checked">
        <a-checkbox v-for="value of options" :key="value" :value>
          {{ value }}
        </a-checkbox>
      </a-checkbox-group>
    </a-modal>
  </a-button>
</template>
